<template>
  <section class="supplier-information">
    <header>
      <el-button v-for="(item, key) in formList" :key="key" :type="`${item.name === activateName ? 'primary' : ''}`"
        :disabled="item.disabled" size="medium" @click="activateName = item.name">{{ item.name }}
      </el-button>
    </header>
    <el-divider />
    <el-tabs el-tabs type="card" tab-position="bottom" v-model="activateName">
      <el-tab-pane v-for="(info, key) in formList" :key="key" :name="info.name">
        <template v-if="info.children">
          <template v-for="(item, key) in info.children">
            <template v-if="item.type === 'staffList'">
              <StaffInformation :id="item.ref" :key="key" :ref="item.ref" :readonly="item.readonly || readonly"
                :rules="item.rules" :dataSource="item.dataSource.map(i => dataSource[i])" :isQualified="isQualified"
                :isClues="isClues" @change="handleChange" />
            </template>
            <template v-else-if="item.type === 'qxbInfo'">
              <QxbInformation
                :id="item.ref"
                :key="key"
                :ref="item.ref"
                :supplierBillInfo="dataSource.supplierBill || {}"
              />
            </template>
            <template v-else-if="item.type === 'bankList'">
              <BankInformation :id="item.ref" :key="key" :ref="item.ref" :readonly="item.readonly || readonly"
                :rules="item.rules" :supplierInfo="dataSource" :dataSource="dataSource[item.dataSource]"
                @change="handleChange" />
            </template>
            <template v-else-if="item.type === 'qualificationList'">
              <QualificationInformation :id="item.ref" :key="key" :ref="item.ref" :readonly="item.readonly || readonly"
                :rules="item.rules" :dataSource="dataSource[item.dataSource]" @change="handleChange" />
            </template>
            <template v-else-if="item.type === 'settlementMethod'">
              <SettlementMethod :id="item.ref" :key="key" :ref="item.ref" :readonly="item.readonly || readonly"
                :rules="item.rules" :dataSource="dataSource[item.dataSource]" :operation="operation"
                @change="handleChange" />
            </template>
            <template v-else-if="item.type === 'rawMaterialInfo'">
              <RawMaterialInfo :id="item.ref" :key="key" :ref="item.ref" :readonly="item.readonly || readonly"
                :rules="item.rules" :dataSource="dataSource[item.dataSource]"
                :contractInfo="dataSource.supplierContractBill || {}" @change="handleChange" :operation="operation" />
            </template>
            <template v-else>
              <el-card :header="item.name" :key="key" :id="item.ref">
                <div slot="header" v-if="item.qixinbao && !item.readonly">
                  <span>工商信息</span>
                  <div class="qixinbao-action" v-if="showQiXinBaoIcon">
                    <img src="@/assets/images/supplier/qixinbao-logo.png" />
                    <el-button @click="getQiXinBaoCompanyInfo" type="text">
                      获取企业信息
                    </el-button>
                  </div>
                </div>
                <SupplierInfoForm :ref="item.ref" :readonly="item.readonly || readonly" :operation="operation"
                  :rules="item.rules || formRules" :formFields="item.formFields" :dataSource="dataSource[item.dataSource]"
                  :showMessage="item.showMessage" @change="handleFormChange" />
              </el-card>
            </template>
          </template>
        </template>
        <template v-else-if="info.type === 'inspectionRecord'">
          <InspectionRecord :key="key" :supplierId="info.id" />
        </template>
        <template v-else-if="info.type === 'changeRecord'">
          <ChangeRecord :key="key" :supplierId="info.id" />
        </template>
        <template v-else>
        </template>
      </el-tab-pane>
    </el-tabs>
    <!-- <pre>{{data}}</pre> -->
    <!-- <pre>{{formData}}</pre> -->
  </section>
</template>

<script>
import { mapState, mapMutations } from 'vuex';
import SupplierInfoForm from '@/pages/supplier/components/supplierInfoForm' // 表单组件
import StaffInformation from '@/pages/supplier/components/supplierStaffInformation' // 人员信息
import BankInformation from '@/pages/supplier/components/bankInformation' // 开户行组件
import QxbInformation from '@/pages/supplier/components/QxbInformation' // 开户行组件
import SettlementMethod from '@/pages/supplier/components/settlementMethod' // 结算方式组件
import RawMaterialInfo from '@/pages/supplier/components/rawMaterialInfo' // 原材料信息组件
import QualificationInformation from '@/pages/supplier/components/qualificationInformation' // 资质信息组件
import InspectionRecord from '@/pages/supplier/components/inspectionRecord.vue' // 考察记录
import ChangeRecord from '@/pages/supplier/components/changeRecord.vue' // 变更记录
import { bankInformation } from '@/pages/supplier/constants'
import { getQiXinBaoCompanyInfo, getSupplierQualificationMenu } from '@/api/supplier/components';
import {
  querySupplierBySupplierNameService,
  validateInvoiceBySupplierNameService
} from '@/api/supplier/management/common';
import { formatDate, filterArrObjItems, filterObjItems, getFiscalPeriodDays } from '@/pages/supplier/utils'
import {
  getRules,
  getExtRules
} from './rules'

const { getInitialFieldsValue } = bankInformation

export default {
  name: 'SupplierTabsForm',
  components: {
    SupplierInfoForm,
    StaffInformation,
    BankInformation,
    QualificationInformation,
    InspectionRecord,
    ChangeRecord,
    SettlementMethod,
    RawMaterialInfo,
    QxbInformation
  },
  props: {
    type: String, // 供应商类型
    list: Array, // 配置信息
    data: Object, // 数据
    operation: Array, // 对比数据
    readonly: { // 表单是否开启禁用
      type: Boolean,
      default: false
    },
  },
  data () {
    return {
      activateName: '',
      qualificationList: [],
      formData: {
        supplierBill: {},
        supplierContractBill: {},
        supplierCooperationAreaBillList: [],
        supplierCooperativeBrandBillList: [],
        supplierManageCategoryBillList: [],
        supplierPayeeBillList: [],
        supplierPersonBillList: [],
        supplierPersonOurBillList: [],
        supplierQualificationBillList: [],
        supplierSettlementBillList: [],
        supplierRawMaterialBillList: [],
      },
    }
  },
  watch: {
    data: {
      handler (newVal, oldVal) {
        // console.log('data update newVal :>> ', newVal);
        // console.log('data update newVal :>> ', JSON.stringify(newVal))
        // console.log('data update oldVal :>> ', oldVal);
        // console.log('data update oldVal :>> ', JSON.stringify(oldVal))
        if (!oldVal && newVal) {
          this.initFormData(_.cloneDeep(newVal))
          // 初始化数据清除错误提示
          this.$nextTick(() => {
            this.clearValidate()
          })
        }
      },
      immediate: true,
      deep: true
    },
    type: {
      handler (val) {
        console.log('供应商类型', val)
        sessionStorage.setItem('supplierType', val)
      },
      immediate: true
    }
  },
  computed: {
    ...mapState('supplier/dict', [
      'dictOptData',
    ]),
    isClues () {
      return this.type === 'clues'
    },
    isPotential () {
      return this.type === 'potential'
    },
    isQualified () {
      return this.type === 'qualified'
    },
    isSpecial () {
      return this.type === 'special'
    },
    isAdd () {
      return !this.dataSource.supplierBill.supplierCode
    },
    dataSource () {
      return this.data
    },
    isEnterprise () {
      return this.dataSource.supplierBill.supplierNatureClassify !== 2
    },
    showQiXinBaoIcon () {
      return !this.readonly && this.isEnterprise
    },
    formList () {
      const { isQualified, isPotential, isEnterprise, data, list, type, $route } = this
      const { name, query } = $route
      const { tab = 0, isReadonlyOtherTabs = 0, disableOtherTabs = 0 } = query
      let configList = JSON.parse(JSON.stringify(list))
      if (!isNaN(tab) && (isReadonlyOtherTabs || disableOtherTabs)) {
        configList.forEach((item, index) => {
          if (tab != index) {
            item.children && item.children.forEach((v) => {
              v.readonly = true
            })
            if (disableOtherTabs) {
              item.disabled = true
            }
          }
        })
      }

      const { supplierBill, supplierContractBill } = data
      const {
        supplierNature, // 基本信息 - 供应商性质
        signContract, // 管理信息 - 是否签合同
        coordination, // 管理信息 - 是否线上协同
      } = supplierBill
      const {
        checkoutTime, rebate, priceBaseOnRawMaterial, paidType, checkoutRange, invoiceType,
        initialCapital, retentionMoney, acceptInvoice, settlementType, purchaseStatus,
        centralizedSettle, packingRequire,
      } = supplierContractBill
      const isSignContract = signContract && signContract === 1 && (isQualified || isPotential)
      const isProduction = supplierNature === 752
      const noProductionFields = ['upstreamSupplier', 'upstreamSupplierStandard', 'sameTradePriceRatio']
      const isNotRebate = !!rebate && rebate === 31
      const isNotPriceBaseOnRawMaterial = priceBaseOnRawMaterial && priceBaseOnRawMaterial === 2
      const rawMaterialFields = ['rawMaterialName', 'rawMaterialPriceRef', 'rawMaterialPriceFloatRate', 'goodsName', 'goodsPriceFloatRate']
      const isNormalInvoice = invoiceType === 101 // 普通发票
      const normalInvoiceFields = ['taxBillRate1', 'taxBillRate2', 'taxBillProvideTime']
      const isVATInvoice = invoiceType === 102 // 增值税专用发票
      const vatInvoiceFields = ['taxBillRate1', 'taxBillRate2']
      const noTaxReceipt = invoiceType === 103 // 无税票
      const noTaxReceiptFields = ['taxBillRate1', 'taxBillRate2', 'taxBillProvideTime', 'miniInvoiceMoney']
      const isCommercialAcceptance = [40290, 40293].includes(settlementType)
      const isAcceptRatio0 = [41, 896, 40904, 40905].includes(settlementType)
      const commercialAcceptanceFields = ['acceptRatio', 'acceptMoney']
      const cashTransferFields = ['acceptRatio', 'acceptMoney', 'acceptPeriod']
      const isBeforeCheckout = [40296, 40297].includes(paidType) && checkoutRange && checkoutRange !== 1101
      const isThreeTypes = ['clues', 'potential', 'qualified'].includes(type)
      const threeDisabledTypes = [1005, 1006, 1007, 1008, 1009, 1010]
      const isPurchaseDisabled = purchaseStatus === 1032
      const isAdd = name.indexOf('add') === 0
      const notCentralizedSettle = centralizedSettle === 31
      const isPackingRequire = packingRequire === 1030

      const changed = isSignContract || isProduction || isNotRebate || isNotPriceBaseOnRawMaterial || invoiceType || initialCapital || retentionMoney || acceptInvoice || settlementType || checkoutTime || isBeforeCheckout || isAcceptRatio0 || isThreeTypes || isPurchaseDisabled || isAdd || notCentralizedSettle
      if (!isEnterprise) {
        if (configList && configList.length && configList[0].name === '基本信息') {
          const formFields = _.compact(configList[0].children[0].formFields.map(i => {
            if (['supplierNatureClassify', 'enterpriseName', 'registerAddress'].includes(i.prop)) {
              if (i.prop === 'enterpriseName') {
                i.label = '姓名'
              }
              if (i.prop === 'registerAddress') {
                i.label = '地址'
                i.disabled = false
              }
              return i
            }
          }))

          configList[0].children[0] = {
            dataSource: 'supplierBill',
            formFields,
            name: '工商信息',
            qixinbao: false,
            ref: 'business-information-form',
            showMessage: true,
          }
        }
      }
      if (changed) {
        return configList.map(item => {
          if (item.children && item.children.length) {
            const children = item.children.map(i => {
              if (i.formFields && i.formFields.length && i.disabled !== true) {
                const formFields = i.formFields.map(j => {
                  let disabled = j.disabled || false
                  // 新增时不禁用项
                  const disabledList = [
                    'supplierType', // 供应商类型
                    'coordination', // 是否线上协同
                    'notOpenReason' // 不开通原因
                  ]
                  if (isAdd && disabledList.includes(j.prop)) {
                    // 供应商类型新增时可编辑
                    disabled = false
                  }
                  if (coordination == 18913 && j.prop === 'notOpenReason') {
                    // 是否线上协同为是，不开通原因禁用
                    disabled = true
                  }
                  if (i.ref === 'rebate-information-form' && j.prop !== 'rebate') {
                    // 是否返利选否时候禁用返利信息字段
                    disabled = isNotRebate
                  }
                  if (isSignContract && j.source && j.source === 'contract') {
                    // 签订合同 禁用合格供应商的来源是合同字段
                    disabled = true
                  }
                  if (isProduction && noProductionFields.includes(j.prop)) {
                    // 生产型时、线上平台时，上游供应商名称、上游供应商合作标准、与其他客户价格差率置灰不能填写；
                    disabled = true
                  }
                  if (isNotPriceBaseOnRawMaterial && rawMaterialFields.includes(j.prop)) {
                    // 约定价格是否依据原材料进行公式核算为否时，禁用原材料名称字段\
                    disabled = true
                  }
                  if (isNormalInvoice && normalInvoiceFields.includes(j.prop)) {
                    // 选择普通发票时，税率1、税率2、税票提供时间不可编辑，最低开票限额（元）可编辑
                    disabled = true
                  }
                  if (noTaxReceipt && noTaxReceiptFields.includes(j.prop)) {
                    // 选择无税票时，税率1、税率2、税票提供时间、最低开票限额（元）不可编辑
                    disabled = true
                  }
                  if (notCentralizedSettle && j.prop === 'centralizedSettlePlace') {
                    // 是否集中结账为否时，集中结账地置灰不能筛选
                    disabled = true
                  }
                  if (acceptInvoice === 2 && cashTransferFields.includes(j.prop)) {
                    // 是否承兑为否，	且承兑金额、承兑比例、承兑期限不可编辑
                    disabled = true
                  }
                  if (isCommercialAcceptance && commercialAcceptanceFields.includes(j.prop)) {
                    // 结算方式选择银行承兑+商业承兑时 承兑金额、承兑比例不可编辑
                    disabled = true
                  }
                  if (isAcceptRatio0 && j.prop === 'acceptRatio') {
                    // 【现金】、【转账】、【信用凭证】、【转账+信用凭证】承兑比例不可编辑
                    disabled = true
                  }
                  if (initialCapital && j.prop === 'initialCapitalCollectType') {
                    // 铺底资金填写金额后，铺底金收取方式可进行选择
                    disabled = false
                  }
                  if (retentionMoney && j.prop === 'retentionMoneyCollectType') {
                    // 质量保证金填写金额后，质保金收取方式可进行选择
                    disabled = false
                  }
                  if ((initialCapital || retentionMoney) && j.prop === 'etcQaExecuteAreaArr') {
                    // 有铺底资金或者质量保证金 铺底质保金执行区域可进行选择
                    disabled = false
                  }
                  if (isBeforeCheckout && j.prop === 'taxBillProvideTime') {
                    // 付款方式选择【货到付款、票到付款】时，结账区间选择不是【 0 】时，则税票提供时间不可编辑
                    disabled = true
                  }
                  if (isPurchaseDisabled && j.prop === 'stopPurchaseReason') {
                    // 进货状态选择【停止】时，则停止进货原因才可编辑
                    disabled = false
                  }
                  if (isPackingRequire && j.prop === 'otherPackRequirements') {
                    // 包装要选择其它时-展示
                    disabled = false
                  }
                  if (checkoutTime) {
                    if (j.prop === 'paidType') {
                      // 已选择结账时间时，则付款方式可进行选择
                      disabled = false
                      // 结账时间为非【固定日结账】时，付款方式只能选择票到付款和货到付款
                      // 结账时间为非【非固定日结账】时，付款方式能选择全部参数
                      // 40294 预付款 40295 带款提货 40296 货到付款 40297 票到付款 40298 背靠背付款 40289 非固定日结账
                      const disabledValues = checkoutTime === 40289 ? [] : [40294, 40295, 40298]
                      if (checkoutTime === 40289 && [820006, 820007, 900002].includes(supplierBill.gainSource)) {
                        const disabledValues = [40294, 40295];
                        return Object.assign({}, j, { disabledValues, disabled })
                      } else {
                        return Object.assign({}, j, { disabledValues, disabled })
                      }
                    }
                    if (j.prop === 'checkoutRange') {
                      if (checkoutTime === 40289) {
                        if ([40294, 40295, 40298].includes(paidType)) {
                          // 付款方式为预付款、带款提货、背靠背付款时，结账区间为0不可修改
                          // const disabledValues = [1102, 1103, 1104, 1105, 1106, 1107, 1108, 1109, 1110, 40747]
                          // return Object.assign({}, j, { disabledValues, disabled })
                          disabled = true
                        }
                      } else {
                        // 结账时间为6-12/ 16-20/26-30/6-12日和26-30日各结一次时，结账区间选择范围：7、10、15、20、30、45、60、90
                        const disabledValues = [1101, 1102, 40747]
                        return Object.assign({}, j, { disabledValues, disabled })
                      }
                    }
                  }
                  if (isVATInvoice && vatInvoiceFields.includes(j.prop)) {
                    // 增值税发票，税率可选参数【不可选 0 】
                    return Object.assign({}, j, { disabledValues: [39874], disabled })
                  }
                  if (isThreeTypes && j.prop === 'supplierType') {
                    // 合格、潜在、线索供应商登记表不可新增内部加工供应商/分公司/物流供应商/财务供应商/落地服务商/通用供应商
                    return Object.assign({}, j, { disabledValues: threeDisabledTypes, disabled })
                  }
                  return Object.assign({}, j, { disabled })
                })
                return Object.assign({}, i, { formFields })
              }
              return Object.assign({}, i)
            })
            return Object.assign({}, item, { children })
          }
          return Object.assign({}, item)
        })
      }
      return configList
    },
    formRules () {
      let rules = {}
      if (this.isClues) {
        rules = {
          ..._.omit(getRules(), 'mainCategoryCode', 'mainCategory', 'manageCategory', 'mainProduct', 'gainSource', 'belongDepartment')
        }
      } else {
        rules = getRules()
      }
      const extRules = getExtRules()
      const { isQualified, isPotential, isEnterprise, data, $route } = this
      const { name } = $route
      const { supplierBill, supplierContractBill, supplierSettlementBillList } = data
      const { supplierNature, canOem, gainSource, projectFiling, signContract, costCalculation, coordination } = supplierBill
      const {
        checkoutTime, // 结账时间
        acceptInvoice, // 是否承兑
        taxBillProvideTime, // 税票提供时间
        taxBillTimeLimit, // 税票提供时限
        taxBillMoneyLimit, // 税票提供限额
        acceptBankRequire, // 承兑银行有无要求
        settlementType, // 结算方式
        purchaseStatus, // 进货状态
        invoiceType, // 发票类型
        centralizedSettle, // 是否集中结账
        initialCapital, // 铺底资金
        retentionMoney, // 质量保证金
        acceptRatio, // 承兑比例
        acceptMoney, // 承兑金额
        rebate, // 是否返利
        rebateInvoice, // 返利是否开票
        packingRequire, // 包装要求
      } = supplierContractBill
      const addRules = (rule) => {
        Object.assign(rules, { [rule]: extRules[rule] })
      }
      const removeRules = (key) => {
        delete rules[key]
      }
      if (isEnterprise) {
        rules.enterpriseName[0].message = '请输入企业名称'
        rules.registerAddress[0].message = '请输入注册地址'
      } else {
        rules.enterpriseName[0].message = '请输入姓名'
        rules.registerAddress[0].message = '请输入地址'
      }
      if (supplierNature) {
        // 生产型 752
        // 小综合: 753
        // 一级代理: 754
        // 二级代理: 1059
        if (supplierNature === 752) {
          // 供应商性质选择为【生产型】时，则厂房地址为【必填】，库房地址为【选填】；
          addRules('plantAddress') // 厂房地址
          addRules('annualOutputValue') // 年产值 生产型必填
          addRules('assemblyLineCount')// 生产流水线数量 生产型必填
          addRules('equipmentCount')// 设备数量 生产型必填
        } else {
          // ‒ 供应商性质选择为【小综合/一级代理/二级代理】时，则厂房地址为【选填】，库房地址为【必填】；
          addRules('storehouseAddress') // 库房地址
          // 非生产型时必须填写
          addRules('upstreamSupplier') // 上游供应商名称
          addRules('upstreamSupplierStandard') // 上游供应商合作标准
          addRules('sameTradePriceRatio') // 与其他客户价格差率
        }
      }
      if (canOem === 1) {
        // 是否代工选择是时，必填
        addRules('oemBrand') // 代工品牌
        addRules('oemGrade') // 档次
      }
      if (gainSource === 799) {
        // 供应商来源为展会时填写
        addRules('exhibitionName') // 展会名称
      }
      if (name.indexOf('add') === 0) {
        addRules('supplierType') // 供应商类型
      }
      if (projectFiling === 18913) {
        // 项目报备选择是时，需填写项目报备内容
        addRules('projectFilingContent') // 报备内容
      }
      if (coordination === 18914) {
        // 线上是否协同选否不开通原因必填
        addRules('notOpenReason')
      }
      if (taxBillProvideTime === 40288) {
        // 结账后 税票提供时间为结账后时，填写
        if (taxBillTimeLimit) {
          addRules('taxBillTimeLimit') // 税票提供时限（天） 2选1
        } else if (taxBillMoneyLimit) {
          addRules('taxBillMoneyLimit') // 税票提供限额（元） 2选1
        } else {
          addRules('taxBillTimeLimit')
          addRules('taxBillMoneyLimit')
        }
      }
      if (acceptInvoice !== 1) {
        removeRules('acceptBankRequire')
      }
      if (acceptBankRequire === 1108) {
        // 承兑银行要求描述选择有时，要求描述必填
        addRules('acceptBankRequireRemark') // 承兑银行要求描述
      }
      // 结算方式 逻辑变更
      if (supplierSettlementBillList) {
        const settlementTypeList = this.formData.supplierSettlementBillList.map(item => item.settlementType)
        // 商业承兑 40919 信用凭证 40920 银行承兑 40921 转账 40922 现金 40923
        if (settlementTypeList.includes(40919)) {
          addRules('commercialAcceptanceTypeArray') // 商业承兑票据类型
        }
        if (settlementTypeList.includes(40920)) {
          addRules('creditAcceptanceType') // 信用票据承兑类型
        }
      }
      // 非合格潜在 或 合格潜在 且 签订合同
      if ((!isQualified && !isPotential) || ((isQualified || isPotential) && signContract !== 1)) {
        // 非合格供应商  或者 合格供应商 且 不签订合同
        // addRules('stockInsurance') // 是否库存保价
        addRules('priceIncreaseNotice') // 涨价提前通知时间
        addRules('cooperativeType') // 合作方式
        addRules('cooperationArea') // 合作区域
        addRules('cooperativeBrand') // 合作品牌
        addRules('salesChannel') // 销售渠道
        addRules('reconciliationDate') // 对账日
        addRules('checkoutTime') // 结账时间
        if (checkoutTime) {
          addRules('paidType') // 付款方式
        }
        addRules('checkoutRange') // 结账区间
        addRules('settlementType') // 结算方式
        addRules('invoiceType') // 发票类型
        addRules('taxBillRate1') // 税票率1
        // addRules('taxBillProvideTime') // 税票提供时间
        addRules('supplyChainFinance') // 供应链金融
        // addRules('acceptInvoice') // 是否承兑
        addRules('retentionMoney') // 质量保证金
        addRules('rebate') // 是否返利
        addRules('arrivalPeriod') // 到货周期
        addRules('freightPayer') // 运费承担方
        addRules('warrantyMonths') // 质量保证期
        addRules('substandardGoodsChangeDays') // 不符合标准商品调换时间
        // 结算方式 40 银行承兑 41 现金 896 转账 40290 商业承兑 40291 转账+银行承兑 40292 转账+商业承兑 40293 银行承兑+商业承兑
        if (settlementType) {
          // 银行承兑
          if (settlementType == 40 || settlementType == 40291) {
            addRules('acceptPeriod') // 承兑期限
          }
          // 商业承兑
          if (settlementType == 40290 || settlementType == 40292) {
            addRules('commercialAcceptancePeriod')
          }
          if (settlementType == 40293) {
            addRules('acceptPeriod') // 承兑期限
            addRules('commercialAcceptancePeriod')
          }
          // 结算方式
          if (settlementType !== 41 && settlementType !== 896) {
            // 非现金 且 非转账
            // addRules('acceptPeriod') // 承兑期限
            if ([40906, 40907, 40291, 40292].includes(settlementType)) {
              // 结算方式选择部分承兑时,承兑比例或承兑金额 ，其一必填
              if (acceptRatio) {
                addRules('acceptRatio') // 承兑比例
              } else if (acceptMoney) {
                addRules('acceptMoney') // 承兑金额
              } else {
                addRules('acceptRatio') // 承兑比例
                addRules('acceptMoney') // 承兑金额
              }
            }

            // if (settlementType === 40904) {
            // // 当选择信用凭证时，比例默认100，需填写信用凭证期限；
            //   addRules('creditScale') // 信用凭证比例
            // } else if ([40905, 40906, 40907].includes(settlementType)) {
            // // 当选择组合方式，例如转账+信用凭证时，需填写信用凭证期限,填写比例，
            //   addRules('creditScale') // 信用凭证比例
            //   addRules('creditTerm') // 信用凭证期限
            // }
          } else {
            // 结算方式为：转账或现金的情况下，承兑银行有无要求字段，为非必填
            // removeRules('acceptBankRequire')
          }
        }

        if (invoiceType) {
          // 选择增值税专用发票时，税率1、税率2，均不可为空，且税票提供时间为必填项
          // 101 普通发
          // 102 增值税专用发票
          // 103 无税票
          if (invoiceType === 102) {
            // 增值税专用发票
            addRules('taxBillProvideTime') // 税票提供时间
            // addRules('taxBillRate1') // 税票率1
            // addRules('taxBillRate2') // 税票率2  税率2 非必填
          } else {
            // 选择普通发票/无税票 税票提供时间不可编辑
            removeRules('taxBillProvideTime') // 税票提供时间
          }
        }
        if (packingRequire === 1030) {
          addRules('otherPackRequirements') // 其它包装要求
        }

        if (rebate === 30) {
          // 返利选是返利信息都必填
          addRules('monthlyRebateStandard')
          addRules('monthlyRebateMoneyStep')
          addRules('monthlyRebateRatio')
          addRules('quarterlyRebateStandard')
          addRules('quarterlyRebateMoneyStep')
          addRules('quarterlyRebateRatio')
          addRules('halfYearRebateStandard')
          addRules('halfYearRebateMoneyStep')
          addRules('halfYearRebateRatio')
          addRules('yearRebateStandard')
          addRules('yearRebateMoneyStep')
          addRules('yearRebateRatio')
          addRules('overallRebateRatio')
          addRules('rebateCalculateType')
          addRules('rebateCalculateLogic')
          addRules('rebateCashType')
          addRules('rebateInvoice')
          addRules('rebateCashDays')
          addRules('includedRebateNextYear')
          addRules('otherRebate')
          if (rebateInvoice === 30) {
            // 返利是否开票为是，返利执行时间必填
            addRules('rebateExecuteTime') // 返利执行时间
          }
        }
      } else {
        // 合格供应商 且 签订合同
        if (rebate === 30) {
          addRules('overallRebateRatio')
          addRules('rebateCalculateType')
          addRules('rebateCalculateLogic')
          addRules('rebateCashType')
          addRules('rebateInvoice')
          addRules('includedRebateNextYear')
          if (rebateInvoice === 30) {
            // 返利是否开票为是，返利执行时间必填
            addRules('rebateExecuteTime') // 返利执行时间
          }
        }
      }
      if (costCalculation === 30) {
        addRules('costCalculationFormula') // 成本核算
      }
      if (purchaseStatus === 1032) {
        // 进货状态选择 停止进货时填写
        addRules('stopPurchaseReason') // 停止进货原因
      }
      if (centralizedSettle === 30) {
        // 选择是集中结账时，集中结账地必填
        addRules('centralizedSettlePlace') // 集中结账地
      }
      if (initialCapital) {
        // 铺底资金大于0时铺底金收取方式必填
        addRules('initialCapitalCollectType') // 铺底金收取方式
      }

      if (initialCapital || retentionMoney) {
        // 铺有铺底资金或者质量保证金 铺底质保金执行区域必填
        addRules('etcQaExecuteAreaArr') // 铺底质保金执行区域
      }

      return rules
    },
    tabList () {
      return this.formList.map(i => i.name)
    },
  },
  created () {
    const { tab } = this.$route.query
    if (tab && !Number.isNaN(tab) && parseInt(tab, 10) < this.tabList.length) {
      this.activateName = this.tabList[parseInt(tab, 10)]
    } else {
      this.activateName = this.tabList[0]
    }
  },
  methods: {
    ...mapMutations('supplier/dict', [
      'setDictOptData',
    ]),
    initFormData (data) {
      for (let [k, v] of Object.entries(data)) {
        if (Array.isArray(v)) {
          if (v.length) {
            if (k === 'supplierCooperativeBrandList') {
              this.formData['supplierCooperativeBrandBillList'] = v
            } else {
              this.formData[k] = v
            }
          }
        } else if (v) {
          this.formData[k] = v
        }
      }

      if (!this.readonly) {
        this.initBankData(data)
        this.initQualificationMenu()
      }
    },
    // 初始化开户行信息
    initBankData (data) {
      const { supplierPayeeBillList, supplierBill } = data
      const { enterpriseName } = supplierBill
      const bankCfg = this.getBankConfig()
      if (bankCfg && supplierPayeeBillList) {
        if (!supplierPayeeBillList.length) {
          if (enterpriseName) {
            // 转化线索供应商需要初始化开票供应商
            this.getSupplierByName(enterpriseName)
          } else {
            // 空数据填充
            this.insertInvoiceSupplier()
            // this.data.supplierPayeeBillList = [getInitialFieldsValue()]
          }
        }
      }
    },
    // 获取开户行信息配置
    getBankConfig () {
      const billing = this.formList.find(i => i.name === '合同信息')
      if (billing && billing.children) {
        return billing.children.find(i => i.type === 'bankList')
      }
      return billing
    },
    //  插入开票供应商数据
    insertInvoiceSupplier (data = {}) {
      const { supplierPayeeBillList: list } = this.data
      const value = Object.assign({ newInvoiceSupplier: data && data.invoiceSupplierId ? 0 : 1 }, getInitialFieldsValue(), data)
      const bankRef = this.$refs['bank-information-list']
      if (list) {
        if (bankRef && bankRef.length) {
          const [payeeBillList] = bankRef
          if (list.length) {
            const { invoiceSupplierId, invoiceSupplierName } = list[0]
            const hasSame = list.find(i => i.invoiceSupplierId === value.invoiceSupplierId && i.invoiceSupplierName === value.invoiceSupplierName)
            if (invoiceSupplierId || invoiceSupplierName) {
              if (!hasSame) {
                // 替换第一行数据
                payeeBillList.setTableData(value, 0)
                // this.$set(this.data.supplierPayeeBillList, 0, value)
                // 保留已有数据
                // this.data.supplierPayeeBillList.unshift(value)
              }
            } else {
              payeeBillList.setTableData(value, 0)
            }
          } else {
            payeeBillList.setTableData(value, 0)
            // this.$set(this.data.supplierPayeeBillList, 0, value)
          }
        } else {
          this.$set(this.data.supplierPayeeBillList, 0, value)
        }
      } else {
        // console.log('data', JSON.stringify(data))
      }
    },
    // 获取默认资质列表
    async initQualificationMenu () {
      const {
        supplierBill,
        supplierManageCategoryBillList: categoryList,
        supplierQualificationBillList: qualifyList,
      } = this.formData
      const { supplierCode, supplierId } = supplierBill
      if (categoryList && categoryList.length) {
        const categoryUuids = categoryList.map(i => i.manageCategoryId)
        const resp = await getSupplierQualificationMenu({ categoryUuids })
        if (resp && resp.status === '0' && resp.result && resp.result.length) {
          const list = resp.result.map((item) => {
            const obj = {
              effectiveDate: '',
              expiryDate: '',
              annex: '',
              qualification: item.quaTypeName,
              qualificationId: item.quaTypeNo,
              ...item
            }
            if (supplierCode && supplierId) {
              Object.assign(obj, { supplierCode, supplierId })
            }
            return obj
          })
          list.unshift(list.splice(list.findIndex(i => i.qualification === '厂家授权书'), 1)[0]);
          list.unshift(list.splice(list.findIndex(i => i.qualification === '营业执照'), 1)[0]);
          // 过滤空资质名称
          const finalList = list.filter(item => item.qualification)
          this.mergeQualificationData(finalList)
        }
      } else if (qualifyList && qualifyList.length) {
        this.data.supplierQualificationBillList = []
      }
    },
    // 合并资质列表
    mergeQualificationData (qualificationList) {
      // console.log('mergeQualificationData :>> ', qualificationList);
      if (!this.data.supplierQualificationBillList || !this.data.supplierQualificationBillList.length) {
        this.data.supplierQualificationBillList = qualificationList
      } else {
        // console.log('this.data.supplierQualificationBillList', this.data.supplierQualificationBillList)
        let list = []
        qualificationList.forEach((item) => {
          const { quaTypeName, qualification } = item
          const arr = this.data.supplierQualificationBillList.filter(i => i.qualification === quaTypeName || i.qualification === qualification)
          arr[0] = Object.assign({}, item, arr[0])
          list = list.concat(arr)
        })
        if (list.length) {
          this.data.supplierQualificationBillList = list
        }
      }
    },
    // 格式化 营业期
    formatBusinessTerm (date) {
      if (!date) {
        return ''
      }
      if (date == '-') {
        return date
      }
      return formatDate(date)
    },
    // 获取企业信息（启信宝）
    async getQiXinBaoCompanyInfo () {
      const { $message, data: dataSource, formList } = this
      const item = formList.map(i => i.children).flat().find(i => i.qixinbao)
      const { enterpriseName } = dataSource[item.dataSource]
      if (!enterpriseName) {
        $message.error(`请输入企业名称!`);
        return
      }
      const params = { companyName: enterpriseName }
      const { status, result, result: { data }, message } = await getQiXinBaoCompanyInfo(params)
      if (status === '0' && result && data) {
        const obj = {
          enterpriseName: data.name,
          legalPerson: data.operName,
          regCapital: data.registCapi,
          paidInCapital: data.actualCapi,
          unifiedSocialCreditCode: data.creditNo,
          establishmentDate: this.formatBusinessTerm(data.startDate),
          approvalDate: this.formatBusinessTerm(data.checkDate),
          organizationCode: data.orgNo,
          businessRegNumber: data.regNo,
          taxpayerIdentityNumber: data.creditNo,
          enterpriseType: data.econKind,
          belongIndustry: data.domain,
          belongRegion: data.districtCode,
          regAuthority: data.belongOrg,
          registerAddress: data.address,
          businessTermStart: this.formatBusinessTerm(data.termStart),
          businessTermEnd: this.formatBusinessTerm(data.termEnd),
          businessTerm: `${this.formatBusinessTerm(data.termStart)},${this.formatBusinessTerm(data.termEnd)}`,
          businessScope: data.scope,
          storehouseAddress: data.address,
          plantAddress: data.address,
        }
        // dataSource[item.dataSource] = Object.assign(dataSource[item.dataSource], obj);
        this.formData.supplierBill = Object.assign(this.formData.supplierBill, obj);
        this.data.supplierBill = Object.assign(this.data.supplierBill, obj);
        if (this.isAdd) {
          this.formData.supplierBill.supplierName = data.name;
          this.data.supplierBill.supplierName = data.name;

          this.getSupplierByName(data.name)
          this.validateInvoiceSupplier(data.name)
        }
      } else {
        $message.error(message);
      }
    },

    // 根据名称查询开票供应商
    async getSupplierByName (supplierName) {
      // 不存在开户行配置
      if (!this.getBankConfig()) {
        return
      }

      if (!this.isAdd) {
        return
      }

      // 查询开票供应商
      const resp = await querySupplierBySupplierNameService({ supplierName })
      if (resp && resp.result && resp.result.length) {
        // 存在开票供应商或者非开票供应商
        this.insertInvoiceSupplier(resp.result[0])
      } else {
        // 不存在供应商
        this.insertInvoiceSupplier({
          newInvoiceSupplier: 1,
          invoiceSupplierName: supplierName,
          payee: supplierName,
        })
      }
    },
    // 校验是否仅开票
    async validateInvoiceSupplier (supplierName) {
      if (!supplierName) {
        return
      }
      if (!this.isPotential && !this.isQualified) {
        return
      }
      const resp = await validateInvoiceBySupplierNameService({ supplierName })
      if (resp && resp.result) {
        const { invoiceSupplier, supplierId, supplierCode } = resp.result
        if (invoiceSupplier === 1) {
          if (this.isAdd) {
            this.$alert('已经存在了一个相同的开票供应商，确定要继续创建吗？', '提示！', {
              confirmButtonText: '确定',
            });
            this.updateSupplierId(supplierId, supplierCode, invoiceSupplier)
          } else {
            this.$alert('已经存在了一个相同的开票供应商，请修改该供应商名称！', '提示！', {
              confirmButtonText: '确定',
            });
            this.resetSupplierId()
          }
        } else {
          this.resetSupplierId()
        }
      } else {
        this.resetSupplierId()
      }
    },
    // 更新各个单据信息
    updateSupplierId (id, code, invoice) {
      const bills = [
        'supplierManageCategoryBillList',
        'supplierPayeeBillList',
        'supplierPersonBillList',
        'supplierPersonOurBillList',
        'supplierQualificationBillList',
      ]
      this.formData.supplierBill.supplierId = id
      this.formData.supplierContractBill.supplierId = id
      this.formData.supplierBill.supplierCode = code
      this.formData.supplierBill.invoiceSupplier = invoice
      bills.forEach(bill => {
        this.formData[bill].forEach(item => {
          item.supplierId = id
          item.supplierCode = code
        })
      })
    },
    // 重置单据信息
    resetSupplierId () {
      const { supplierId, supplierCode, invoiceSupplier } = this.data.supplierBill
      this.updateSupplierId(supplierId, supplierCode, invoiceSupplier)
    },
    // 表格值变化回调
    handleChange (data) {
      const { value, prop } = data
      // console.log(`${prop} update:>> `, JSON.stringify(value));
      if (Array.isArray(value)) {
        if (prop === 'supplierQualificationBillList') {
          const list = value
            .filter(i => i.effectiveDate && i.annex && i.expiryDate)
            .map((item, index) => {
              item.ord = index + 1
              return this.filterData(item)
            })
          this.formData[prop] = list
        } else if (prop === 'supplierPayeeBillList') {
          this.formData[prop] = value.filter(i => i.invoiceSupplierName)
        } else if (prop === 'supplierSettlementBillList') {
          // 结算方式 变更
          const list = value.map(item => this.filterData(item))
          this.formData[prop] = list
          const settlementTypeList = this.formData.supplierSettlementBillList.map(item => item.settlementType)
          // 商业承兑 40919 信用凭证 40920 银行承兑 40921 转账 40922 现金 40923
          if (settlementTypeList.includes(40919) || settlementTypeList.includes(40921)) {
            // 是否承兑 = 是
            this.data.supplierContractBill.acceptInvoice = 1
            this.formData.supplierContractBill.acceptInvoice = 1
          } else if (settlementTypeList.includes(40920) || settlementTypeList.includes(40922) || settlementTypeList.includes(40923)) {
            // 是否承兑 = 否
            this.data.supplierContractBill.acceptInvoice = 2
            this.formData.supplierContractBill.acceptInvoice = 2
          }
        } else {
          const list = value.map(item => this.filterData(item))
          this.formData[prop] = list
        }
      } else {
        this.formData[prop] = this.filterData(value)
      }
    },
    // 表单值变化回调
    handleFormChange (data) {
      console.log(data)
      const { value, prop, label } = data
      if (typeof value === 'object') {
        console.log(`${label} ${prop} updated --:>> `, JSON.stringify(value));
      } else {
        console.log(`${label} ${prop} updated --:>>`, value);
      }
      let {
        supplierBill,
        supplierContractBill,
      } = this.formData
      // const { supplierName, supplierCode, supplierId } = supplierBill
      const calculateEtcQaRatio = (initialCapital = 0, retentionMoney = 0) => {
        let result = 0
        const { lastYearPurchaseAmount } = this.formData.supplierBill
        if (lastYearPurchaseAmount) {
          result = (initialCapital + retentionMoney) / lastYearPurchaseAmount * 100
          supplierContractBill.etcQaRatio = result.toFixed(3)
          this.data.supplierContractBill.etcQaRatio = result.toFixed(3)
        }
      }
      switch (prop) {
        case 'rebate':
          supplierContractBill.rebate = value
          this.data.supplierContractBill.rebate = value
          // 返利信息 是否返利切换 清空返利信息
          if (this.data.supplierContractBill.rebate == 31) {
            const rebateFormFields = this.$refs['rebate-information-form'][0].formFields.filter(item => item.prop != 'rebate')
            const rebateFormFieldsNum = rebateFormFields.filter(item => item.type == 'number').map(i => i.prop)
            const rebateFormFieldsStr = rebateFormFields.filter(item => item.type !== 'number').map(i => i.prop)
            rebateFormFieldsNum.forEach(item => {
              supplierContractBill[item] = null
              this.data.supplierContractBill[item] = null
            })
            rebateFormFieldsStr.forEach(item => {
              supplierContractBill[item] = ''
              this.data.supplierContractBill[item] = ''
            })
          }
          break;
        case 'enterpriseName':
          supplierBill.enterpriseName = value
          if (!this.isEnterprise && value) {
            this.getSupplierByName(value)
          }
          break;
        case 'mainCategory':
          // 主营品类
          supplierBill.categoryProductType = value.categoryProductType
          supplierBill.mainCategory = value.categoryName
          supplierBill.mainCategoryCode = value.categoryNo
          supplierBill.mainCategoryId = value.uuid
          supplierBill.metal = parseInt(value.isMetal, 10)
          // 1：危化品 2:管制刀具 3:非限制 危化品 禁用集中结账地 法人结算中心选项
          if (this.isQualified) {
            let newData = _.cloneDeep(this.dictOptData);
            newData[224].forEach(item => {
              if (value.categoryProductType == 1 && item.value == 901) {
                this.data.supplierContractBill.centralizedSettle = 30
                supplierContractBill.centralizedSettle = 30
                if (this.data.supplierContractBill.centralizedSettlePlace == 901) {
                  this.data.supplierContractBill.centralizedSettlePlace = ''
                }
                item.disable = 0
              } else if (value.categoryProductType != 1 && item.value == 901) {
                item.disable = 1
              }
            })
            this.setDictOptData(newData)
          }

          if (this.isSpecial) {
            console.log('isSpecial: ', value.categoryNo)
            // 分公司
            if (value.categoryNo === '81010101') {
              this.data.supplierBill.supplierType = 1006
              supplierBill.supplierType = 1006
            }
            // 通用供应商
            if (value.categoryNo === '81020101') {
              this.data.supplierBill.supplierType = 1010
              supplierBill.supplierType = 1010
            }
            // 财务供应商
            if (value.categoryNo === '81050101') {
              this.data.supplierBill.supplierType = 1008
              supplierBill.supplierType = 1008
            }
            // 内部加工
            if (value.categoryNo === '81060101') {
              this.data.supplierBill.supplierType = 1005
              supplierBill.supplierType = 1005
            }
          }
          break;
        case 'manageCategory':
          // 经营品类
          this.formData.supplierManageCategoryBillList = value.map(({ categoryUuid, categoryNo, categoryName, categoryProductType }) => {
            // if (supplierId) {
            //   obj.supplierId = supplierId
            //   obj.supplierCode = supplierCode
            //   obj.supplierName = supplierName
            // }
            return {
              manageCategory: categoryName,
              manageCategoryCode: categoryNo,
              manageCategoryId: categoryUuid,
              categoryProductType,
            }
          })
          let dictObj = _.cloneDeep(this.dictOptData);
          dictObj[224].forEach(item => {
            if (value.some(item => item.categoryProductType == 1) && item.value == 901) {
              this.data.supplierContractBill.centralizedSettle = 30
              supplierContractBill.centralizedSettle = 30
              if (this.data.supplierContractBill.centralizedSettlePlace == 901) {
                this.data.supplierContractBill.centralizedSettlePlace = ''
              }
              item.disable = 0
            } else if (value.every(item => item.categoryProductType != 1) && item.value == 901) {
              item.disable = 1
            }
          })
          this.setDictOptData(dictObj)
          this.initQualificationMenu()
          break;
        case 'marketValueRemark':
          // 面价执行说明
          supplierBill.marketValueRemark = value.response.result
          break;
        case 'supplierType':
          // 供应商类型
          supplierBill.supplierType = value
          if (value) {
            // 内部加工供应商、分公司、物流供应商、财务供应商、落地服务商 是否对账选否；其他都是：是
            if ([1005, 1006, 1007, 1008, 1009].includes(value)) {
              this.data.supplierContractBill.reconciliation = 31
              supplierContractBill.reconciliation = 31
            } else {
              this.data.supplierContractBill.reconciliation = 30
              supplierContractBill.reconciliation = 30
            }
            if (value === 1002) {
              this.$alert('加工供应商指的是我司支付加工费的供应商，若我司最终支付的是购买成品的价格，应该为供货供应商，不应选择加工供应商，请慎重选择。', '温馨提示', {
                confirmButtonText: '确定'
              });
            }
          }
          break;
        case 'coordination':
          // 是否线上协同
          supplierBill.coordination = value
          // 询价单是否协同
          this.data.supplierBill.inquiryBillCoordination = value
          supplierBill.inquiryBillCoordination = value
          // 是 清空不开通原因
          if (value == 18913) {
            this.data.supplierBill.notOpenReason = ''
            supplierBill.notOpenReason = ''
          }
          break;
        case 'generalTaxpayer':
          // 纳税人类型
          supplierContractBill.generalTaxpayer = value
          // 发票类型 = 增值税发票
          supplierContractBill.invoiceType = 102
          this.data.supplierContractBill.invoiceType = 102
          // 一般纳税人 30 小规模纳税人 31
          if (value == 30) {
            // 0.13
            supplierContractBill.taxBillRate1 = 39879
            this.data.supplierContractBill.taxBillRate1 = 39879
          } else if (value == 31) {
            // 0.03
            supplierContractBill.taxBillRate1 = 39875
            this.data.supplierContractBill.taxBillRate1 = 39875
          }
          break;
        case 'paidType':
          // 付款方式 40294 预付款 40295 带款提货 40296 货到付款 40297 票到付款 40298 背靠背付款
          supplierContractBill.paidType = value
          if ([40294, 40295, 40298].includes(value)) {
            // 当付款方式选择【预付款、贷款提货、背靠背付款】时，则结账区间默认为【 0 】，即税票提供时间可进行编辑
            supplierContractBill.checkoutRange = 1101
            this.data.supplierContractBill.checkoutRange = 1101
          }

          if ([40296, 40297].includes(value)) {
            // 当付款方式选择【货到付款、票到付款】时，则结账区间为可编辑
            // 结账区间选择不是【 0 】时，则税票提供时间可编辑，
            // 结账区间选择是【 0 】时，则税票提供时间不可编辑，且默认值为【结账前】
            if (this.data.supplierContractBill.checkoutRange === 1101) {
              // 结账区间为【0】
              supplierContractBill.taxBillProvideTime = 40287
              this.data.supplierContractBill.taxBillProvideTime = 40287
            }
          }

          // if ([40295, 40297].includes(value)) {
          if ([40295].includes(value)) {
            // 带款提货，结账区间默认为0，税票提供时间默认为结账后
            // 票到付款，税票提供时间默认为结账后
            if (value === 40295) {
              supplierContractBill.checkoutRange = 1101
              this.data.supplierContractBill.checkoutRange = 1101
            }

            supplierContractBill.taxBillProvideTime = 40288
            this.data.supplierContractBill.taxBillProvideTime = 40288
          }
          getFiscalPeriodDays(supplierContractBill, this.data.supplierContractBill)
          break;
        case 'checkoutTime':
          // 结账时间 42 6-12日 43 16-20日 44 26-30日 45 6-12日和26-30日各结一次 40289 非固定日结账
          supplierContractBill.checkoutTime = value
          const { paidType, checkoutRange } = this.data.supplierContractBill
          supplierBill.gainSource = this.data.supplierBill.gainSource
          if (value !== 40289 && [40294, 40295, 40298].includes(paidType)) {
            supplierContractBill.paidType = undefined
            this.data.supplierContractBill.paidType = undefined
          }
          if (value !== 40289 && [1101, 1102, 40747].includes(checkoutRange)) {
            supplierContractBill.checkoutRange = undefined
            this.data.supplierContractBill.checkoutRange = undefined
          }
          getFiscalPeriodDays(supplierContractBill, this.data.supplierContractBill)
          break;
        case 'checkoutRange':
          // 结账区间
          supplierContractBill.checkoutRange = value
          if (value !== 1101 && [40296, 40297].includes(this.data.supplierContractBill.paidType)) {
            // 当付款方式选择【货到付款、票到付款】时，则结账区间为可编辑
            // 结账区间选择不是【 0 】时，则税票提供时间不可编辑，且默认值为【结账前】
            supplierContractBill.taxBillProvideTime = 40287
            this.data.supplierContractBill.taxBillProvideTime = 40287
          }
          getFiscalPeriodDays(supplierContractBill, this.data.supplierContractBill)
          break;
        case 'acceptBankRequireRemark':
          // 承兑银行要求描述
          supplierContractBill.acceptBankRequireRemark = value.response.result
          break;
        case 'costCalculationFormula':
          // 成本核算公式表
          supplierBill.costCalculationFormula = value.response.result
          break;
        case 'supplierName':
          // 供应商名称
          supplierBill.supplierName = value
          this.validateInvoiceSupplier(value)
          break;
        case 'managementAreaId':
          // 供应商管理区域
          supplierBill.managementAreaId = value.manageAreaId
          supplierBill.managementAreaName = value.manageAreaName
          break;
        case 'businessContact':
          // 公司业务对接人
          supplierBill.businessContact = value ? value.userId : ''
          supplierBill.businessContactName = value ? value.userName : ''
          break;
        case 'etcQaExecuteAreaArr':
          // 铺底质保金执行区域
          supplierContractBill.etcQaExecuteArea = value && value.length ? value.map(i => i.manageAreaId).join() : ''
          break;
        case 'cooperationArea':
          // 合作区域
          this.formData.supplierCooperationAreaBillList = value.map(({ addressCode, addressName }) => {
            // if (supplierId) {
            //   obj.supplierId = supplierId
            //   obj.supplierCode = supplierCode
            //   obj.supplierName = supplierName
            // }
            return {
              areaId: addressCode,
              areaName: addressName,
            }
          })
          break;
        case 'cooperativeBrand':
          // 合作品牌
          this.formData.supplierCooperativeBrandBillList = value.map(({ brandId, brandName }) => {
            return {
              brandId,
              brandName,
            }
          })
          break;
        case 'salesChannelArr':
          // 销售渠道
          supplierContractBill.salesChannel = value.join()
          break;
        case 'initialCapital':
          // 铺底资金
          supplierContractBill.initialCapital = value
          calculateEtcQaRatio(value, this.data.supplierContractBill.retentionMoney)
          if (!value) {
            this.data.supplierContractBill.initialCapitalCollectType = undefined
            supplierContractBill.initialCapitalCollectType = undefined
            if (!this.data.supplierContractBill.retentionMoney) {
              this.data.supplierContractBill.etcQaExecuteAreaArr = []
              supplierContractBill.etcQaExecuteArea = ''
            }
          }
          break;
        case 'retentionMoney':
          // 质量保证金
          supplierContractBill.retentionMoney = value
          calculateEtcQaRatio(this.data.supplierContractBill.initialCapital, value)
          if (!value && !this.data.supplierContractBill.initialCapital) {
            this.data.supplierContractBill.etcQaExecuteAreaArr = []
            supplierContractBill.etcQaExecuteArea = ''
          }
          break;
        case 'warrantyPeriod':
          // 保质/保修期
          supplierContractBill.warrantyPeriod = value
          break;
        case 'warrantyPeriodStandard':
          // 保质/保修期标准
          supplierContractBill.warrantyPeriodStandard = value
          break;
        case 'qualityCompensation':
          // 质量赔付标准
          supplierContractBill.qualityCompensation = value
          break;
        case 'salesSupport':
          // 售后支持标准
          supplierContractBill.salesSupport = value
          break;
        case 'signContract':
          // 是否签合同
          supplierContractBill.signContract = value
          if (value && value === 2) {
            // 是否签订合同选择否时，约定价格是否依据原材料进行公式核算默认成否
            this.data.supplierContractBill.priceBaseOnRawMaterial = 2
            supplierContractBill.priceBaseOnRawMaterial = 2
          }
          break;
        case 'settlementType':
          // 结算方式
          supplierContractBill.settlementType = value
          if (value === 41 || value === 896) {
            // 结算方式为【现金/转账】，是否承兑为【否】
            this.data.supplierContractBill.acceptInvoice = 2
            supplierContractBill.acceptInvoice = 2
          } else if (value) {
            // 其他得选项，是否承兑为【是】
            this.data.supplierContractBill.acceptInvoice = 1
            supplierContractBill.acceptInvoice = 1
          }
          if ([40, 40290, 40293].includes(value)) {
            // 【银行承兑】、【商业承兑】、【银行承兑+商业承兑】承兑比例默认为100%
            this.data.supplierContractBill.acceptRatio = 100
            supplierContractBill.acceptRatio = 100
          }
          if ([41, 896, 40904, 40905].includes(value)) {
            // 【现金】、【转账】、【信用凭证】、【转账+信用凭证】承兑比例默认为0%
            this.data.supplierContractBill.acceptRatio = 0
            supplierContractBill.acceptRatio = 0
          }

          break
        case 'invoiceType':
          // 发票类型
          supplierContractBill.invoiceType = value
          switch (value) {
            case 101:
            case 103:
              // 普票/无票，税率默认为【0】
              this.data.supplierContractBill.taxBillRate1 = 39874
              this.data.supplierContractBill.taxBillRate2 = 39874
              supplierContractBill.taxBillRate1 = 39874
              supplierContractBill.taxBillRate2 = 39874
              break;
            case 102:
              if (this.data.supplierContractBill.taxBillRate1 === 39874) {
                this.data.supplierContractBill.taxBillRate1 = undefined
                supplierContractBill.taxBillRate1 = undefined
              }
              if (this.data.supplierContractBill.taxBillRate2 === 39874) {
                this.data.supplierContractBill.taxBillRate2 = undefined
                supplierContractBill.taxBillRate2 = undefined
              }
              break;
          }
          break;
        case 'purchaseStatus':
          // 进货状态
          supplierBill.purchaseStatus = value
          if (value === 1031) {
            this.data.supplierContractBill.stopPurchaseReason = ''
            supplierBill.stopPurchaseReason = ''
          }
          break;
        case 'stopPurchaseReason':
          // 停止进货原因
          supplierBill.stopPurchaseReason = value
          break;
        case 'lastYearPurchaseAmount':
          // 去年进货额
          supplierBill.lastYearPurchaseAmount = value
          const { initialCapital, retentionMoney } = this.data.supplierContractBill
          calculateEtcQaRatio(initialCapital, retentionMoney)
          break;
        case 'yearPurchaseAmount':
          // 本年进货额
          supplierBill.yearPurchaseAmount = value
          break;
        case 'purchaseAddRatio':
          // 进货涨浮比例
          supplierBill.purchaseAddRatio = value
          break;
        default:
          if (prop && supplierBill.hasOwnProperty(prop)) {
            supplierBill[prop] = value
          }
          if (prop && supplierContractBill.hasOwnProperty(prop)) {
            supplierContractBill[prop] = value
          }
          break;
      }
    },
    // 获取表单数据
    // isValidity 先验证表单，通过后返回数据
    getData (isValidity = false) {
      return new Promise(async (resolve, reject) => {
        // 验证各个表单
        for (let i = 0; i < this.formList.length; i++) {
          const info = this.formList[i];
          if (!info.children) {
            break
          }
          for (let j = 0; j < info.children.length; j++) {
            const item = info.children[j];
            const [component] = this.$refs[item.ref]
            if (!component || item.readonly) {
              break
            }
            if (isValidity) {
              const res = await component.getValidate()
              if (res) {
                this.activateName = this.tabList[i]
                this.scrollTopAnimate(item.ref)
                // reject(res)
                if (item.ref === 'business-information-form' && this.formData.supplierBill.supplierNatureClassify !== 2) {
                  this.$message.error('请输入正确的企业名称，并点击“获取企业信息”')
                }
                return
              }
            }
          }
        }
        const obj = {}
        for (let [k, v] of Object.entries(this.formData)) {
          if (Array.isArray(v)) {
            if (v.length > 1) {
              obj[k] = filterArrObjItems(v)
            } else if (v.length === 1 && Object.keys(v[0]).length) {
              obj[k] = filterArrObjItems(v)
            } else {
              obj[k] = []
            }
          } else if (Object.keys(v).length) {
            obj[k] = filterObjItems(v)
          }
        }

        // 返回数据
        resolve(obj)
      })
    },
    // 过滤掉空字段
    filterData (data) {
      if (data) {
        const isEmptyObj = (obj) => {
          return Object.values(obj).every((value) => {
            return !value && value !== 0
          })
        }
        const filterEmptyObj = (data) => {
          if (isEmptyObj(data)) {
            return Object.create(null)
          } else {
            return data
          }
        }
        if (Array.isArray(data)) {
          return _.compact(filterArrObjItems(data).map((item) => {
            if (isEmptyObj(filterEmptyObj(item))) {
              return null
            }
            return filterEmptyObj(item)
          }))
        } else if (typeof data === 'object') {
          return filterEmptyObj(filterObjItems(data))
        } else {
          return null
        }
      } else {
        return null
      }
    },
    scrollTopAnimate (id) {
      this.$nextTick(() => {
        document.querySelector('.i-layout-content-main')
          .scrollTo({ top: document.getElementById(id).offsetTop, behavior: 'smooth' })
      })
    },
    // 清空表单验证
    clearValidate () {
      for (let i = 0; i < this.formList.length; i++) {
        const info = this.formList[i];
        if (!info.children) {
          break
        }
        for (let j = 0; j < info.children.length; j++) {
          const item = info.children[j];
          const [component] = this.$refs[item.ref]
          // console.log(`${item.ref}`, component)
          component.clearValidate && component.clearValidate()
        }
      }
    }
  }
}
</script>

<style lang="less">
.supplier-information {
  #billing-method-form {
    margin-top: 1px;
  }

  header {
    text-align: center;
    margin-bottom: 10px;
  }

  .el-tabs__header .el-tabs__nav.is-bottom {
    display: none;
  }

  .el-card+.el-card {
    margin-top: 16px;
  }

  .qixinbao-action {
    float: right;
    display: flex;
    margin: 0;
    padding: 0;

    img {
      height: 20px;
      margin-right: 4px;
    }

    button {
      margin: 0;
      padding: 0;
    }
  }

  &+.actions {
    margin-top: 16px;
    text-align: center;
  }
}
</style>
